package com.yzcrm.erp.admin.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.tx.TxSerializable;
import com.yzcrm.common.config.exception.YzcrmException;
import com.yzcrm.common.constant.BaseConstant;
import com.yzcrm.erp.admin.entity.*;
import com.yzcrm.erp.crm.common.CheckStatusEnum;
import com.yzcrm.erp.crm.common.CrmEnum;
import com.yzcrm.erp.crm.entity.CrmActionRecord;
import com.yzcrm.erp.crm.entity.CrmBusiness;
import com.yzcrm.erp.crm.entity.CrmContract;
import com.yzcrm.erp.crm.entity.CrmCustomer;
import com.yzcrm.erp.crm.entity.CrmLeads;
import com.yzcrm.erp.crm.entity.CrmPreSales;
import com.yzcrm.erp.crm.entity.CrmReceivables;
import com.yzcrm.erp.crm.service.CrmCustomerService;
import com.yzcrm.erp.crm.service.CrmLeadsService;
import com.yzcrm.erp.finance.entity.FinancePurchase;
import com.yzcrm.erp.psi.common.PsiUtil;
import com.yzcrm.erp.psi.entity.PsiEnterLeaveStock;
import com.yzcrm.erp.psi.service.PsiEnterLeaveStockService;
import com.yzcrm.erp.crm.entity.CrmQuotationCombination;
import com.yzcrm.utils.BaseUtil;
import com.yzcrm.utils.R;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;


import java.util.*;

public class AdminExamineRecordService {

    @Inject
    private AdminDeptService  adminDeptService;

    @Inject
    private CrmLeadsService crmLeadsService;
    @Inject
    private CrmCustomerService crmCustomerService;

    @Inject
    private PsiEnterLeaveStockService psiEnterLeaveStockService;

    /**
     * 第一次添加审核记录和审核日志
     *
     * @param userId 授权审批人
     *               type 审批模块: 1-合同，2-回款，3-线索，4-客户，5-商机
     */
    @Before(Tx.class)
    public Map<String, Integer> saveExamineRecord(Integer type, Long userId, Long ownerUserId, Integer recordId, Integer status){
        Map<String, Integer> map = new HashMap<>();
        //创建审核记录
        AdminExamineRecord examineRecord = new AdminExamineRecord();
        if (recordId != null) {
            examineRecord = AdminExamineRecord.dao.findById(recordId);
            Db.update(Db.getSql("admin.examineLog.updateExamineLogIsRecheckByRecordId"), recordId);
        } else {
            examineRecord.setCreateTime(DateUtil.date());
            examineRecord.setCreateUser(BaseUtil.getUser().getUserId());
        }
        //创建审核日志
        AdminExamineLog examineLog = new AdminExamineLog();
        examineLog.setCreateTime(DateUtil.date());
        examineLog.setCreateUser(BaseUtil.getUser().getUserId());
        if (status != null) {
            examineLog.setExamineStatus(5);
            examineRecord.setExamineStatus(5);
        } else {
            examineLog.setExamineStatus(0);
            examineRecord.setExamineStatus(0);
        }
        examineLog.setOrderId(1);
        //根据type查询当前启用审批程
        AdminExamine examine = AdminExamine.dao.findFirst(Db.getSql("admin.examine.getExamineByCategoryType"), type);
        if (examine == null) {
            map.put("status", 0);
        } else {
            examineRecord.setExamineId(examine.getExamineId());
            //先判断该审批流程是否为固定审批
            if (examine.getExamineType() == 1) {
                //固定审批
                //先查询该审批流程的审批步骤的第一步
                AdminExamineStep examineStep = AdminExamineStep.dao.findFirst(Db.getSql("admin.examineStep.queryExamineStepByExamineIdOrderByStepNum"), examine.getExamineId());
                examineRecord.setExamineStepId(examineStep.getStepId());
                examineLog.setExamineStepId(examineStep.getStepId());
                if (recordId == null) {
                    examineRecord.save();
                } else {
                    examineRecord.update();
                }
                if (status != null) {
                    map.put("status", 1);
                    map.put("id", examineRecord.getRecordId());
                    return map;
                }
                if (examineStep.getStepType() == 2 || examineStep.getStepType() == 3) {
                    String[] userIds = examineStep.getCheckUserId().split(",");
                    for (String id : userIds) {
                        if (StrUtil.isNotEmpty(id)) {
                            examineLog.setLogId(null);
                            examineLog.setExamineUser(Long.valueOf(id));
                            examineLog.setRecordId(examineRecord.getRecordId());
                            examineLog.setIsRecheck(0);
                            examineLog.save();
                        }
                    }
                } else if (examineStep.getStepType() == 1) {
                    //	如果是负责人主管审批 获取主管ID
                    Record r = Db.findFirst(Db.getSql("admin.examineLog.queryUserByUserId"), ownerUserId);
                    if (r == null || r.getLong("user_id") == null) {
                        examineLog.setExamineUser(BaseConstant.SUPER_ADMIN_USER_ID);
                    } else {
                        examineLog.setExamineUser(r.getLong("user_id"));
                    }

                    examineLog.setRecordId(examineRecord.getRecordId());
                    examineLog.setIsRecheck(0);
                    examineLog.save();

                } else {
                    //	如果是负责人主管审批 获取主管的主管ID
                    Record r = Db.findFirst(Db.getSql("admin.examineLog.queryUserByUserId"), Db.findFirst(Db.getSql("admin.examineLog.queryUserByUserId"), ownerUserId).getLong("user_id"));
                    if (r == null || r.getLong("user_id") == null) {
                        examineLog.setExamineUser(BaseConstant.SUPER_ADMIN_USER_ID);
                    } else {
                        examineLog.setExamineUser(r.getLong("user_id"));
                    }
                    examineLog.setRecordId(examineRecord.getRecordId());
                    examineLog.setIsRecheck(0);
                    examineLog.save();
                }

            } else {
                //授权审批
                examineLog.setExamineUser(userId);
                if (recordId == null) {
                    examineRecord.save();
                } else {
                    examineRecord.update();
                }
                examineLog.setRecordId(examineRecord.getRecordId());
                if (userId != null) {
                    examineLog.save();
                }
            }

            map.put("status", 1);
            map.put("id", examineRecord.getRecordId());
        }
        return map;
    }

    /**
     * 判断是否是倒数第二个审核
     *
     * @param recordId
     * @param label
     * @return
     */
    public R nextToLastExamineUser(Integer recordId, Integer label) {

        Boolean canAddExamineUser = false;

        CrmEnum crmEnum = CrmEnum.parse(label);
        if (ObjectUtil.isNull(crmEnum) || crmEnum.getType() < CrmEnum.FINANCE_OFFICE_PURCHASE.getType() || crmEnum.getType() > CrmEnum.FINANCE_OTHER_PURCHASE.getType()) {
            return R.ok().put("data", Kv.by("canAddExamineUser", canAddExamineUser));
        }

        //当前审批人
        Long auditUserId = BaseUtil.getUser().getUserId();
        //判断是否审批通过
        boolean is_examine_pass = false;
        //根据审核记录id查询审核记录
        AdminExamineRecord examineRecord = AdminExamineRecord.dao.findById(recordId);
        //【判断当前审批人是否有审批权限
        Record reco = Db.findFirst(Db.getSqlPara("admin.examineLog.queryExamineLog",
                Kv.by("recordId", recordId).set("auditUserId", auditUserId).set("stepId", examineRecord.getExamineStepId())));
        if (reco == null) {
            return R.error("当前用户没有审批权限！");
        }


        //查询审批流程
        AdminExamine examine = AdminExamine.dao.findById(examineRecord.getExamineId());

        //查询下下一个审批步骤，如果不存在
        AdminExamineStep nextExamineStep =
                AdminExamineStep.dao.findFirst(Db.getSql("admin.examineStep.queryExamineStepByNextExamineIdOrderByStepId"), examine.getExamineId(), examineRecord.getExamineStepId());
        if (ObjectUtil.isNotNull(nextExamineStep)) {
            nextExamineStep =
                    AdminExamineStep.dao.findFirst(Db.getSql("admin.examineStep.queryExamineStepByNextExamineIdOrderByStepId"), examine.getExamineId(), nextExamineStep.getStepId());
            if (ObjectUtil.isNull(nextExamineStep)) {
                canAddExamineUser = true;
            }
        }


//        // 判断是否是有连续同一人审批 TODO 重复审批，删除下一个重复人
//        while(nextExamineStep != null) {
//
//            String userId;
//            if (nextExamineStep.getStepType() == 1) {
//                // 上级审批
//
//                Record r = Db.findFirst(Db.getSql("admin.examineLog.queryUserByUserId"), ownerUserId);
//                if (r == null || r.getLong("user_id") == null) {
//                    userId = BaseConstant.SUPER_ADMIN_USER_ID.toString();
//                } else {
//                    userId = r.getLong("user_id").toString();
//                }
//
//            } else {
//
//                userId = nextExamineStep.getCheckUserId();
//            }
//
//
//        }


        return R.ok().put("data", Kv.by("canAddExamineUser", canAddExamineUser));
    }

    /**
     * 审核合同或者回款 recordId:审核记录id status:审批状态：审核状态  1 审核通过 2 审核拒绝 4 已撤回
     * remarks:审核备注 id:审核对象的id（合同或者回款或线索的id）nextUserId:下一个审批人 ownerUserId:负责人:转化为客户的负责人 customerOwnerId
     */
    @Before(TxSerializable.class)
    public R auditExamine(Integer recordId, Integer status, String remarks, String batchId, Integer id, Long nextUserId, Long ownerUserId, Long newOwnerId, JSONObject jsonObject, Long checkUserId, Integer customerType) {

        String msg = "";

        //当前审批人
        Long auditUserId = BaseUtil.getUser().getUserId();
        //判断是否审批通过
        boolean is_examine_pass = false;
        //根据审核记录id查询审核记录
        AdminExamineRecord examineRecord = AdminExamineRecord.dao.findById(recordId);
        if (status == 4) {
            if (!examineRecord.getCreateUser().equals(auditUserId) && !auditUserId.equals(BaseConstant.SUPER_ADMIN_USER_ID)) {
                return R.error("当前用户没有审批权限！");
            }
        } else {
            //【判断当前审批人是否有审批权限
            Record reco = Db.findFirst(Db.getSqlPara("admin.examineLog.queryExamineLog",
                    Kv.by("recordId", recordId).set("auditUserId", auditUserId).set("stepId", examineRecord.getExamineStepId())));
            if (reco == null) {
                return R.error("当前用户没有审批权限！");
            }
        }
        examineRecord.setExamineStatus(status);
        examineRecord.setBatchId(batchId);
        //查询审批流程
        AdminExamine examine = AdminExamine.dao.findById(examineRecord.getExamineId());
        switch (examine.getCategoryType()) {
            case 1:
                ownerUserId = CrmContract.dao.findById(id).getOwnerUserId();
                break;
            case 2:
                ownerUserId = CrmReceivables.dao.findById(id).getOwnerUserId();
                break;
            case 3:
                ownerUserId = CrmLeads.dao.findById(id).getOwnerUserId();
                break;
            case 4:
                ownerUserId = CrmCustomer.dao.findById(id).getOwnerUserId();
                break;
            case 5:
                ownerUserId = CrmBusiness.dao.findById(id).getOwnerUserId();
                break;
            case 11:
                ownerUserId = CrmPreSales.dao.findById(id).getOwnerUserId();
                break;
            default:


                if (CrmEnum.PSI_SALES_ENTER.getType() == examine.getCategoryType()
                        || CrmEnum.PSI_RETRUN_ENTER.getType() == examine.getCategoryType()
                        || CrmEnum.PSI_REPAIR_ENTER.getType() == examine.getCategoryType()
                        || CrmEnum.PSI_TEST_ENTER.getType() == examine.getCategoryType()
                        || CrmEnum.PSI_INVENTORY_PROFIT_ENTER.getType() == examine.getCategoryType()
                        || CrmEnum.PSI_OTHER_ENTER.getType() == examine.getCategoryType()
                        || CrmEnum.PSI_PURCHASE_ENTER.getType() == examine.getCategoryType()
                        || CrmEnum.PSI_SALES_LEAVE.getType() == examine.getCategoryType()
                        || CrmEnum.PSI_BORROW_LEAVE.getType() == examine.getCategoryType()
                        || CrmEnum.PSI_REPAIR_LEAVE.getType() == examine.getCategoryType()
                        || CrmEnum.PSI_TEST_LEAVE.getType() == examine.getCategoryType()
                        || CrmEnum.PSI_INVENTORY_LOSS_LEAVE.getType() == examine.getCategoryType()
                        || CrmEnum.PSI_OTHER_LEAVE.getType() == examine.getCategoryType()) {
                    // 出入库

                    ownerUserId = PsiEnterLeaveStock.dao.findById(id).getOwnerUserId();

                } else if (CrmEnum.FINANCE_PURCHASE.getType() == examine.getCategoryType()
                        || CrmEnum.FINANCE_OFFICE_PURCHASE.getType() == examine.getCategoryType()
                        || CrmEnum.FINANCE_NORMAL_PURCHASE.getType() == examine.getCategoryType()
                        || CrmEnum.FINANCE_PROJECT_PURCHASE.getType() == examine.getCategoryType()
                        || CrmEnum.FINANCE_DEV_PURCHASE.getType() == examine.getCategoryType()
                        || CrmEnum.FINANCE_OTHER_PURCHASE.getType() == examine.getCategoryType()) {
                    // 采购申请

                    ownerUserId = FinancePurchase.dao.findById(id).getOwnerUserId();

                }
                // 报价审核通过
                if (CrmEnum.CRM_QUOTATION_COMBINATION.getType() == examine.getCategoryType()) {
                    ownerUserId = Long.valueOf(CrmQuotationCombination.dao.findById(id).getOwnerUserId());
                }
                break;
        }

        //查询当前审批步骤
        AdminExamineStep examineStep = AdminExamineStep.dao.findById(examineRecord.getExamineStepId());
        //查询当前审核日志
        AdminExamineLog nowadayExamineLog = null;
        if (examine.getExamineType() == 1) {
            // 1 固定审批
            nowadayExamineLog = AdminExamineLog.dao.findFirst(Db.getSql("admin.examineLog.queryNowadayExamineLogByRecordIdAndStepId"), examineRecord.getRecordId(), examineRecord.getExamineStepId(), auditUserId);
        } else {
            // 2 授权审批
            nowadayExamineLog = AdminExamineLog.dao.findFirst(Db.getSql("admin.examineLog.queryNowadayExamineLogByRecordIdAndStatus"), examineRecord.getRecordId(), auditUserId);
        }

        //审核日志 添加审核人
        if (nowadayExamineLog != null) {
            nowadayExamineLog.setExamineTime(DateUtil.date());
            nowadayExamineLog.setRemarks(remarks);
            nowadayExamineLog.setBatchId(batchId);
        }

        if (status == 2) {
            //判断审核拒绝
            nowadayExamineLog.setExamineStatus(status);
            if (examineStep != null && examineStep.getStepType() == 2) {
                examineRecord.setExamineStatus(3);
                Record record = Db.findFirst(Db.getSqlPara("admin.examineLog.queryCountByStepId", Kv.by("recordId", recordId).set("stepId", examineStep.getStepId())));
                if (record.getInt("toCount") == 0) {
                    examineRecord.setExamineStatus(status);
                }
            }

            switch (examine.getCategoryType()) {
                case 1:
                    //合同
                    Db.update(Db.getSql("crm.contract.updateCheckStatusById"), status, id);
                    break;
                case 2:
                    //回款
                    Db.update(Db.getSql("crm.receivables.updateCheckStatusById"), status, id);
                    break;
                case 3:
                    //线索
                    Db.update(Db.getSql("crm.leads.updateCheckStatusById"), status, id);
                    break;
                case 4:
                    //客户
                    Db.update(Db.getSql("crm.customer.updateCheckStatusById"), status, id);
                    break;
                case 5:
                    //商机
                    Db.update(Db.getSql("crm.business.updateCheckStatusById"), status, id);
                    break;
                case 11:
                    //售前申请
                    Db.update(Db.getSql("crm.preSales.updateCheckStatusById"), status, id);
                    break;
                default:


                    if (CrmEnum.PSI_SALES_ENTER.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_RETRUN_ENTER.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_REPAIR_ENTER.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_TEST_ENTER.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_INVENTORY_PROFIT_ENTER.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_OTHER_ENTER.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_PURCHASE_ENTER.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_SALES_LEAVE.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_BORROW_LEAVE.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_REPAIR_LEAVE.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_TEST_LEAVE.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_INVENTORY_LOSS_LEAVE.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_OTHER_LEAVE.getType() == examine.getCategoryType()) {
                        // 出入库

                        Db.update(Db.getSql("psi.enterLeaveStock.updateCheckStatusById"), status, id);

                    } else if (CrmEnum.FINANCE_PURCHASE.getType() == examine.getCategoryType()
                            || CrmEnum.FINANCE_OFFICE_PURCHASE.getType() == examine.getCategoryType()
                            || CrmEnum.FINANCE_NORMAL_PURCHASE.getType() == examine.getCategoryType()
                            || CrmEnum.FINANCE_PROJECT_PURCHASE.getType() == examine.getCategoryType()
                            || CrmEnum.FINANCE_DEV_PURCHASE.getType() == examine.getCategoryType()
                            || CrmEnum.FINANCE_OTHER_PURCHASE.getType() == examine.getCategoryType()) {
                        // 采购申请

                        Db.update(Db.getSql("finance.purchase.updateCheckStatusById"), status, id);
                    }
                    // 拒绝报价审核
                    if (CrmEnum.CRM_QUOTATION_COMBINATION.getType() == examine.getCategoryType()) {
                        Db.update(Db.getSql("crm.quotationComb.updateCheckStatusById"), status, id);
                    }
                    break;
            }
        } else if (status == 4) {
            //先查询该审批流程的审批步骤的第一步
            AdminExamineStep oneExamineStep = AdminExamineStep.dao.findFirst(Db.getSql("admin.examineStep.queryExamineStepByExamineIdOrderByStepNum"), examine.getExamineId());
            //判断审核撤回
            AdminExamineLog examineLog = new AdminExamineLog();
            examineLog.setBatchId(batchId);
            examineLog.setLogId(null);
            examineLog.setExamineUser(auditUserId);
            examineLog.setCreateTime(DateUtil.date());
            examineLog.setCreateUser(auditUserId);
            examineLog.setExamineStatus(status);
            examineLog.setExamineTime(new Date());
            examineLog.setIsRecheck(0);
            if (examine.getExamineType() == 1) {
                examineRecord.setExamineStepId(oneExamineStep.getStepId());
                examineLog.setExamineStepId(examineStep.getStepId());
                examineLog.setOrderId(examineStep.getStepNum());
            } else {
                Integer orderId = Db.queryInt(Db.getSql("admin.examineStep.queryExamineStepOrderId"), recordId);
                if (orderId == null) {
                    orderId = 1;
                }
                examineLog.setOrderId(orderId);
            }
            examineLog.setRecordId(examineRecord.getRecordId());
            examineLog.setRemarks(remarks);
            examineLog.save();
            switch (examine.getCategoryType()) {
                case 1:
                    //合同
                    CrmContract contract = CrmContract.dao.findById(id);
                    if (contract.getCheckStatus() == 1) {
                        return R.error("该合同已审核通过，不能撤回！");
                    }
                    Db.update(Db.getSql("crm.contract.updateCheckStatusById"), 4, id);
                    break;
                case 2:
                    //回款
                    CrmReceivables receivables = CrmReceivables.dao.findById(id);
                    if (receivables.getCheckStatus() == 1) {
                        return R.error("该回款已审核通过，不能撤回！");
                    }
                    Db.update(Db.getSql("crm.receivables.updateCheckStatusById"), 4, id);
                    break;
                case 3:
                    //线索
                    CrmLeads leads = CrmLeads.dao.findById(id);
                    if (leads.getCheckStatus() == 1) {
                        return R.error("该线索已审核通过，不能撤回！");
                    }
                    Db.update(Db.getSql("crm.leads.updateCheckStatusById"), 4, id);
                    break;
                case 4:
                    //客户
                    CrmCustomer customer = CrmCustomer.dao.findById(id);
                    if (customer.getCheckStatus() == 1) {
                        return R.error("该客户已审核通过，不能撤回！");
                    }
                    Db.update(Db.getSql("crm.customer.updateCheckStatusById"), 4, id);
                    break;
                case 5:
                    //商机
                    CrmBusiness business = CrmBusiness.dao.findById(id);
                    if (business.getCheckStatus() == 1) {
                        return R.error("该商机已审核通过，不能撤回！");
                    }
                    Db.update(Db.getSql("crm.business.updateCheckStatusById"), 4, id);
                    break;
                case 11:
                    //售前
                    CrmPreSales preSales = CrmPreSales.dao.findById(id);
                    if (preSales.getCheckStatus() == 1) {
                        return R.error("该商机已审核通过，不能撤回！");
                    }
                    Db.update(Db.getSql("crm.preSales.updateCheckStatusById"), 4, id);
                    break;
                default:


                    if (CrmEnum.PSI_SALES_ENTER.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_RETRUN_ENTER.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_REPAIR_ENTER.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_TEST_ENTER.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_INVENTORY_PROFIT_ENTER.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_OTHER_ENTER.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_PURCHASE_ENTER.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_SALES_LEAVE.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_BORROW_LEAVE.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_REPAIR_LEAVE.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_TEST_LEAVE.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_INVENTORY_LOSS_LEAVE.getType() == examine.getCategoryType()
                            || CrmEnum.PSI_OTHER_LEAVE.getType() == examine.getCategoryType()) {
                        // 出入库

                        PsiEnterLeaveStock enterLeaveStock = PsiEnterLeaveStock.dao.findById(id);
                        if (enterLeaveStock.getCheckStatus() == CheckStatusEnum.CHECK_STATUS_OK.getType()) {
                            throw new YzcrmException("该出入库已审核通过，不能撤回！");
                        }
                        Db.update(Db.getSql("psi.enterLeaveStock.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_UNDO.getType(), id);

                    } else if (CrmEnum.FINANCE_PURCHASE.getType() == examine.getCategoryType()
                            || CrmEnum.FINANCE_OFFICE_PURCHASE.getType() == examine.getCategoryType()
                            || CrmEnum.FINANCE_NORMAL_PURCHASE.getType() == examine.getCategoryType()
                            || CrmEnum.FINANCE_PROJECT_PURCHASE.getType() == examine.getCategoryType()
                            || CrmEnum.FINANCE_DEV_PURCHASE.getType() == examine.getCategoryType()
                            || CrmEnum.FINANCE_OTHER_PURCHASE.getType() == examine.getCategoryType()) {
                        // 采购申请

                        FinancePurchase financePurchase = FinancePurchase.dao.findById(id);
                        if (financePurchase.getCheckStatus() == CheckStatusEnum.CHECK_STATUS_OK.getType()) {
                            throw new YzcrmException("该采购已审核通过，不能撤回！");
                        }
                        Db.update(Db.getSql("finance.purchase.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_UNDO.getType(), id);

                    }
                    if (CrmEnum.CRM_QUOTATION_COMBINATION.getType() == examine.getCategoryType()) {
                        CrmQuotationCombination quotationCombination = CrmQuotationCombination.dao.findById(id);
                        if (quotationCombination.getCheckStatus() == CheckStatusEnum.CHECK_STATUS_OK.getType()) {
                            throw new YzcrmException("该报价已审核通过，不能撤回！");
                        }
                        Db.update(Db.getSql("crm.quotationComb.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_UNDO.getType(), id);
                    }
                    break;
            }
        } else {

            // 采购审核 倒数第二次审核动态增加审核人
            if (ObjectUtil.isNotNull(checkUserId)) {
//                if (checkUserId == 3) {
//                    Record record = Db.findFirst("SELECT log_id,examine_status,examine_user FROM yzcrm_admin_examine_log WHERE FIND_IN_SET(3,examine_user) AND record_id = ?", recordId);
//                    Long examineUser = record.getLong("examine_user");
//                    if (!ObjectUtil.isNotNull(examineUser)) {
//                        if (!checkUserId.equals(examineUser)) {
//                            saveAdminExamineLog(batchId, checkUserId, examineRecord, examineStep);
//                        }
//                    }
//                } else {
//                    saveAdminExamineLog(batchId, checkUserId, examineRecord, examineStep);
//                }
                saveAdminExamineLog(batchId, checkUserId, examineRecord, examineStep);
            }


            //审核通过
            nowadayExamineLog.setExamineStatus(status);
            //判断该审批流程类型
            if (examine.getExamineType() == 1) {
                //固定审批

                //查询下一个审批步骤
                AdminExamineStep nextExamineStep =
                        AdminExamineStep.dao.findFirst(Db.getSql("admin.examineStep.queryExamineStepByNextExamineIdOrderByStepId"), examine.getExamineId(), examineRecord.getExamineStepId());

                boolean flag = true;
                //判断是否是并签
                if (examineStep.getStepType() == 3) {
                    //查询当前并签是否都完成
                    //根据审核记录ID，审核步骤ID，查询审核日志
                    // List<AdminExamineLog> examineLogs = AdminExamineLog.dao.find(Db.getSql("admin.examineLog.queryNowadayExamineLogByRecordIdAndStepId"),examineRecord.getRecordId(),examineRecord.getExamineStepId());
                    //当前并签人员
                    nowadayExamineLog.update();
                    String[] userIds = examineStep.getCheckUserId().split(",");
                    for (String userId : userIds) {
                        if (StrUtil.isNotEmpty(userId)) {
                            AdminExamineLog examineLog = AdminExamineLog.dao.findFirst(Db.getSql("admin.examineLog.queryNowadayExamineLogByRecordIdAndStepId"), examineRecord.getRecordId(), examineRecord.getExamineStepId(), userId);
                            if (examineLog.getExamineStatus() == 0) {
                                //并签未走完
                                flag = false;
                                break;
                            }
                        }
                    }
                    //并签未完成
                    if (!flag) {
                        examineRecord.setExamineStatus(3);
                        switch (examine.getCategoryType()) {
                            case 1:
                                //合同
                                Db.update(Db.getSql("crm.contract.updateCheckStatusById"), 3, id);
                                break;
                            case 2:
                                //回款
                                Db.update(Db.getSql("crm.receivables.updateCheckStatusById"), 3, id);
                                break;
                            case 3:
                                //线索
                                Db.update(Db.getSql("crm.leads.updateCheckStatusById"), 3, id);
                                break;
                            case 4:
                                //客户
                                Db.update(Db.getSql("crm.customer.updateCheckStatusById"), 3, id);
                                break;
                            case 5:
                                //商机
                                Db.update(Db.getSql("crm.business.updateCheckStatusById"), 3, id);
                                break;
                            case 11:
                                //售前
                                Db.update(Db.getSql("crm.preSales.updateCheckStatusById"), 3, id);
                                break;
                            default:


                                if (CrmEnum.PSI_SALES_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_RETRUN_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_REPAIR_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_TEST_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_INVENTORY_PROFIT_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_OTHER_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_PURCHASE_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_SALES_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_BORROW_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_REPAIR_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_TEST_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_INVENTORY_LOSS_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_OTHER_LEAVE.getType() == examine.getCategoryType()) {
                                    // 出入库

                                    Db.update(Db.getSql("psi.enterLeaveStock.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_CHECKING.getType(), id);

                                } else if (CrmEnum.FINANCE_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_OFFICE_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_NORMAL_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_PROJECT_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_DEV_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_OTHER_PURCHASE.getType() == examine.getCategoryType()) {
                                    // 采购申请

                                    Db.update(Db.getSql("finance.purchase.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_CHECKING.getType(), id);

                                }
                                // 报价
                                if (CrmEnum.CRM_QUOTATION_COMBINATION.getType() == examine.getCategoryType()) {
                                    Db.update(Db.getSql("crm.quotationComb.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_CHECKING.getType(), id);
                                }
                                break;
                        }
                    }
                } else {

                    // 当前或签人员
                    nowadayExamineLog.update();

                    // 查找是否有必须审批
                    List<AdminExamineLog> listAdminExamineLog = AdminExamineLog.dao.find(Db.getSql("admin.examineLog.queryNowadayExamineLogByRecordIdAndStepIdMustCheck"), examineRecord.getRecordId(), examineRecord.getExamineStepId());
                    for (int i = 0; i < listAdminExamineLog.size(); i++) {

                        AdminExamineLog examineLog = listAdminExamineLog.get(i);
                        if (examineLog.getExamineStatus() == 0) {
                            // 后加的必须审核 为未审核
                            flag = false;
                            break;
                        }
                    }

                    // 后加的必须审核 为未审核
                    if (!flag) {


                        // 将原有的未审批的“或审批”删除
                        Db.delete("delete from yzcrm_admin_examine_log where record_id = ? and examine_step_id = ? and must_check = 0 and examine_status=0", examineRecord.getRecordId(), examineRecord.getExamineStepId());


                        examineRecord.setExamineStatus(3);
                        switch (examine.getCategoryType()) {
                            case 1:
                                //合同
                                Db.update(Db.getSql("crm.contract.updateCheckStatusById"), 3, id);
                                break;
                            case 2:
                                //回款
                                Db.update(Db.getSql("crm.receivables.updateCheckStatusById"), 3, id);
                                break;
                            case 3:
                                //线索
                                Db.update(Db.getSql("crm.leads.updateCheckStatusById"), 3, id);
                                break;
                            case 4:
                                //客户
                                Db.update(Db.getSql("crm.customer.updateCheckStatusById"), 3, id);
                                break;
                            case 5:
                                //商机
                                Db.update(Db.getSql("crm.business.updateCheckStatusById"), 3, id);
                                break;
                            case 11:
                                //售前
                                Db.update(Db.getSql("crm.preSales.updateCheckStatusById"), 3, id);
                                break;
                            default:


                                if (CrmEnum.PSI_SALES_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_RETRUN_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_REPAIR_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_TEST_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_INVENTORY_PROFIT_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_OTHER_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_PURCHASE_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_SALES_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_BORROW_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_REPAIR_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_TEST_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_INVENTORY_LOSS_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_OTHER_LEAVE.getType() == examine.getCategoryType()) {
                                    // 出入库

                                    Db.update(Db.getSql("psi.enterLeaveStock.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_CHECKING.getType(), id);

                                } else if (CrmEnum.FINANCE_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_OFFICE_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_NORMAL_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_PROJECT_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_DEV_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_OTHER_PURCHASE.getType() == examine.getCategoryType()) {
                                    // 采购申请

                                    Db.update(Db.getSql("finance.purchase.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_CHECKING.getType(), id);

                                }
                                // 报价
                                if (CrmEnum.CRM_QUOTATION_COMBINATION.getType() == examine.getCategoryType()) {
                                    Db.update(Db.getSql("crm.quotationComb.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_CHECKING.getType(), id);
                                }
                                break;
                        }
                    }
//                    // 判断是否有后加的必须审核
//                    if(nowadayExamineLog.getMustCheck() != 1) {
//
//
//
//                    }
                }
                if (flag) {


                    // 判断是否是有连续同一人审批 TODO 重复审批，删除下一个重复人
                    while (nextExamineStep != null) {

                        String userId;
                        if (nextExamineStep.getStepType() == 1) {
                            // 上级审批

                            Record r = Db.findFirst(Db.getSql("admin.examineLog.queryUserByUserId"), ownerUserId);
                            if (r == null || r.getLong("user_id") == null) {
                                userId = BaseConstant.SUPER_ADMIN_USER_ID.toString();
                            } else {
                                userId = r.getLong("user_id").toString();
                            }

                        } else {

                            userId = nextExamineStep.getCheckUserId();
                        }

                        if (BaseUtil.getUserId().toString().equals(userId)) {
                            // 如果当前审批人和下一个审批人相同

                            // 继续查找下一个审批步骤
                            nextExamineStep =
                                    AdminExamineStep.dao.findFirst(Db.getSql("admin.examineStep.queryExamineStepByNextExamineIdOrderByStepId"), examine.getExamineId(), nextExamineStep.getExamineId());

                        } else {

                            break;
                        }
                    }


                    //判断是否有下一步流程
                    if (nextExamineStep != null) {
                        //有下一步流程
                        examineRecord.setExamineStatus(3);
                        examineRecord.setExamineStepId(nextExamineStep.getStepId());

                        AdminExamineLog examineLog = new AdminExamineLog();
                        examineLog.setOrderId(nextExamineStep.getStepNum());
                        examineLog.setBatchId(batchId);
                        if (nextExamineStep.getStepType() == 2 || nextExamineStep.getStepType() == 3) {
                            //并签或者或签
                            String[] userIds = nextExamineStep.getCheckUserId().split(",");
                            for (String uid : userIds) {
                                if (StrUtil.isNotEmpty(uid)) {
                                    examineLog.setLogId(null);
                                    examineLog.setExamineUser(Long.valueOf(uid));
                                    examineLog.setCreateTime(DateUtil.date());
                                    examineLog.setCreateUser(BaseUtil.getUser().getUserId());
                                    examineLog.setExamineStatus(0);
                                    examineLog.setIsRecheck(0);
                                    examineLog.setExamineStepId(nextExamineStep.getStepId());
                                    examineLog.setRecordId(examineRecord.getRecordId());

                                    examineLog.save();
                                }
                            }
                        } else if (nextExamineStep.getStepType() == 1) {
                            Record r = Db.findFirst(Db.getSql("admin.examineLog.queryUserByUserId"), ownerUserId);
                            examineLog.setLogId(null);
                            if (r == null || r.getLong("user_id") == null) {
                                examineLog.setExamineUser(BaseConstant.SUPER_ADMIN_USER_ID);
                            } else {
                                examineLog.setExamineUser(r.getLong("user_id"));

                            }
                            examineLog.setExamineStatus(0);
                            examineLog.setCreateTime(DateUtil.date());
                            examineLog.setCreateUser(BaseUtil.getUser().getUserId());
                            examineLog.setIsRecheck(0);
                            examineLog.setExamineStepId(nextExamineStep.getStepId());
                            examineLog.setRecordId(examineRecord.getRecordId());
                            examineLog.save();
                        } else {
                            Record r = Db.findFirst(Db.getSql("admin.examineLog.queryUserByUserId"), Db.findFirst(Db.getSql("admin.examineLog.queryUserByUserId"), ownerUserId).getLong("user_id"));
                            examineLog.setLogId(null);
                            AdminUser adminUser = AdminUser.dao.findById(nowadayExamineLog.getExamineUser());
                            if (adminUser != null && adminUser.getParentId() != null) {
                                examineLog.setExamineUser(adminUser.getParentId());
                            } else {
                                examineLog.setExamineUser(ownerUserId);
                            }

                            examineLog.setExamineStatus(0);
                            examineLog.setCreateTime(DateUtil.date());
                            examineLog.setCreateUser(BaseUtil.getUser().getUserId());
                            examineLog.setExamineStepId(nextExamineStep.getStepId());
                            examineLog.setRecordId(examineRecord.getRecordId());
                            examineLog.setIsRecheck(0);
                            examineLog.save();
                        }
                        switch (examine.getCategoryType()) {
                            case 1:
                                //合同
                                Db.update(Db.getSql("crm.contract.updateCheckStatusById"), 3, id);
                                break;
                            case 2:
                                //回款
                                Db.update(Db.getSql("crm.receivables.updateCheckStatusById"), 3, id);
                                break;
                            case 3:
                                //线索
                                Db.update(Db.getSql("crm.leads.updateCheckStatusById"), 3, id);
                                break;
                            case 4:
                                //客户
                                Db.update(Db.getSql("crm.customer.updateCheckStatusById"), 3, id);
                                break;
                            case 5:
                                //商机
                                Db.update(Db.getSql("crm.business.updateCheckStatusById"), 3, id);
                                break;
                            case 11:
                                //售前
                                Db.update(Db.getSql("crm.preSales.updateCheckStatusById"), 3, id);
                                break;
                            default:


                                if (CrmEnum.PSI_SALES_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_RETRUN_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_REPAIR_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_TEST_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_INVENTORY_PROFIT_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_OTHER_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_PURCHASE_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_SALES_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_BORROW_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_REPAIR_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_TEST_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_INVENTORY_LOSS_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_OTHER_LEAVE.getType() == examine.getCategoryType()) {
                                    // 出入库

                                    Db.update(Db.getSql("psi.enterLeaveStock.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_CHECKING.getType(), id);

                                } else if (CrmEnum.FINANCE_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_OFFICE_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_NORMAL_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_PROJECT_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_DEV_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_OTHER_PURCHASE.getType() == examine.getCategoryType()) {
                                    // 采购申请

                                    Db.update(Db.getSql("finance.purchase.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_CHECKING.getType(), id);

                                }
                                // 报价
                                if (CrmEnum.CRM_QUOTATION_COMBINATION.getType() == examine.getCategoryType()) {
                                    Db.update(Db.getSql("crm.quotationComb.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_CHECKING.getType(), id);
                                }
                                break;
                        }
                    } else {
                        switch (examine.getCategoryType()) {
                            case 1:
                                //合同
                                Db.update(Db.getSql("crm.contract.updateCheckStatusById"), 1, id);
                                CrmContract contract = CrmContract.dao.findById(id);
                                Db.update(Db.getSql("crm.customer.updateDealStatusById"), "1", contract.getCustomerId());
                                break;
                            case 2:
                                //回款
                                Db.update(Db.getSql("crm.receivables.updateCheckStatusById"), 1, id);
                                break;
                            case 3:
                                //线索审核通过
                                is_examine_pass = true;
                                break;
                            case 4:
                                //客户
                                Db.update(Db.getSql("crm.customer.updateCheckStatusById"), 1, id);
                                //客户审批通过，客户类型为用户选择的类型，默认为目标客户
                                Db.update(Db.getSql("crm.customer.updateCustomerTypeById"), (customerType != null ? customerType : 2), id);
                                //更新责任人
                                if (newOwnerId != null) {
                                    if (newOwnerId == 0) {
                                        //放入公海
                                        Db.update(Db.getSql("crm.customer.updateNewOwnerUserId"), null, id);
                                    } else {
                                        //指定客户负责人
                                        Db.update(Db.getSql("crm.customer.updateNewOwnerUserId"), newOwnerId, id);
                                    }
                                }
                                break;
                            case 5:
                                //商机
                                Db.update(Db.getSql("crm.business.updateCheckStatusById"), 1, id);
                                break;
                            case 11:
                                //售前
                                Db.update(Db.getSql("crm.preSales.updateCheckStatusById"), 1, id);
                                //更新责任人
                                if(newOwnerId != null) {
                                	Db.update(Db.getSql("crm.preSales.updatePreSalesOwnerId"), newOwnerId, id);
                                }
                                //审核通过，更新对应商机的阶段至技术方案阶段
                                Kv kv1 = new Kv();
                                kv1.set("label",11).set("id",id).set("statusId",3);
                                updateBusinessStatusId(kv1);
                                break;
                            default:


                                if (CrmEnum.PSI_SALES_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_RETRUN_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_REPAIR_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_TEST_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_INVENTORY_PROFIT_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_OTHER_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_PURCHASE_ENTER.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_SALES_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_BORROW_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_REPAIR_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_TEST_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_INVENTORY_LOSS_LEAVE.getType() == examine.getCategoryType()
                                        || CrmEnum.PSI_OTHER_LEAVE.getType() == examine.getCategoryType()) {
                                    // 出入库

                                    is_examine_pass = true;

                                } else if (CrmEnum.FINANCE_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_OFFICE_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_NORMAL_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_PROJECT_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_DEV_PURCHASE.getType() == examine.getCategoryType()
                                        || CrmEnum.FINANCE_OTHER_PURCHASE.getType() == examine.getCategoryType()) {
                                    // 采购申请

                                    Db.update(Db.getSql("finance.purchase.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_OK.getType(), id);

                                }
                                // 报价
                                if (CrmEnum.CRM_QUOTATION_COMBINATION.getType() == examine.getCategoryType()) {
                                    Db.update(Db.getSql("crm.quotationComb.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_OK.getType(), id);
                                    //审核通过，更新对应商机的阶段至订单合同阶段
                                    Kv kv2 = new Kv();
                                    kv2.set("label",750).set("id",id).set("statusId",6);
                                    updateBusinessStatusId(kv2);
                                }
                                break;
                        }

                    }
                }
            } else {
                //授权审批
                if (nextUserId != null) {
                    //有下一审批人
                    examineRecord.setExamineStatus(3);
                    AdminExamineLog examineLog = new AdminExamineLog();
                    examineLog.setBatchId(batchId);
                    examineLog.setCreateTime(DateUtil.date());
                    examineLog.setCreateUser(BaseUtil.getUser().getUserId());
                    examineLog.setExamineUser(nextUserId);
                    examineLog.setExamineStatus(0);
                    examineLog.setIsRecheck(0);
                    examineLog.setRecordId(examineRecord.getRecordId());
                    examineLog.setOrderId(nowadayExamineLog.getOrderId() + 1);
                    examineLog.save();
                    switch (examine.getCategoryType()) {
                        case 1:
                            //合同
                            Db.update(Db.getSql("crm.contract.updateCheckStatusById"), 3, id);
                            break;
                        case 2:
                            //回款
                            Db.update(Db.getSql("crm.receivables.updateCheckStatusById"), 3, id);
                            break;
                        case 3:
                            //线索
                            Db.update(Db.getSql("crm.leads.updateCheckStatusById"), 3, id);
                            break;
                        case 4:
                            //客户
                            Db.update(Db.getSql("crm.customer.updateCheckStatusById"), 4, id);
                            break;
                        case 5:
                            //商机
                            Db.update(Db.getSql("crm.business.updateCheckStatusById"), 4, id);
                            break;
                        case 11:
                            //售前
                            Db.update(Db.getSql("crm.preSales.updateCheckStatusById"), 4, id);
                            break;
                        default:


                            if (CrmEnum.PSI_SALES_ENTER.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_RETRUN_ENTER.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_REPAIR_ENTER.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_TEST_ENTER.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_INVENTORY_PROFIT_ENTER.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_OTHER_ENTER.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_PURCHASE_ENTER.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_SALES_LEAVE.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_BORROW_LEAVE.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_REPAIR_LEAVE.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_TEST_LEAVE.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_INVENTORY_LOSS_LEAVE.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_OTHER_LEAVE.getType() == examine.getCategoryType()) {
                                // 出入库

                                Db.update(Db.getSql("psi.enterLeaveStock.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_CHECKING.getType(), id);

                            } else if (CrmEnum.FINANCE_PURCHASE.getType() == examine.getCategoryType()
                                    || CrmEnum.FINANCE_OFFICE_PURCHASE.getType() == examine.getCategoryType()
                                    || CrmEnum.FINANCE_NORMAL_PURCHASE.getType() == examine.getCategoryType()
                                    || CrmEnum.FINANCE_PROJECT_PURCHASE.getType() == examine.getCategoryType()
                                    || CrmEnum.FINANCE_DEV_PURCHASE.getType() == examine.getCategoryType()
                                    || CrmEnum.FINANCE_OTHER_PURCHASE.getType() == examine.getCategoryType()) {
                                // 采购申请

                                Db.update(Db.getSql("finance.purchase.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_CHECKING.getType(), id);

                            }
                            // 报价
                            if (CrmEnum.CRM_QUOTATION_COMBINATION.getType() == examine.getCategoryType()) {
                                Db.update(Db.getSql("crm.quotationComb.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_CHECKING.getType(), id);
                            }
                            break;
                    }
                } else {
                    //没有下一审批人
                    switch (examine.getCategoryType()) {
                        case 1:
                            //合同
                            Db.update(Db.getSql("crm.contract.updateCheckStatusById"), 1, id);
                            CrmContract contract = CrmContract.dao.findById(id);
                            Db.update(Db.getSql("crm.customer.updateDealStatusById"), 1, contract.getCustomerId());
                            break;
                        case 2:
                            //回款
                            Db.update(Db.getSql("crm.receivables.updateCheckStatusById"), 1, id);
                            break;
                        case 3:
                            //线索审核通过
                            is_examine_pass = true;
                            break;
                        case 4:
                            //客户
                            Db.update(Db.getSql("crm.customer.updateCheckStatusById"), 1, id);
                            //客户审批通过，客户类型为用户选择的类型，默认为目标客户
                            Db.update(Db.getSql("crm.customer.updateCustomerTypeById"), (customerType != null ? customerType : 2), id);
                            //更新责任人
                            if (newOwnerId != null) {
                                if (newOwnerId == 0) {
                                    //放入公海
                                    Db.update(Db.getSql("crm.customer.updateNewOwnerUserId"), null, id);
                                } else {
                                    //指定客户负责人
                                    Db.update(Db.getSql("crm.customer.updateNewOwnerUserId"), newOwnerId, id);
                                }
                            }

                            break;
                        case 5:
                            //商机
                            Db.update(Db.getSql("crm.business.updateCheckStatusById"), 1, id);
                            break;
                        case 11:
                            //设备清单审核
                            Db.update(Db.getSql("crm.preSales.updateCheckStatusById"), 1, id);
                            //更新责任人
                            if(newOwnerId != null) {
                            	Db.update(Db.getSql("crm.preSales.updatePreSalesOwnerId"), newOwnerId, id);
                            }
                            //审核通过，更新对应商机的阶段至技术方案阶段
                            Kv kv1 = new Kv();
                            kv1.set("label",11).set("id",id).set("statusId",3);
                            updateBusinessStatusId(kv1);
                            break;
                        default:


                            if (CrmEnum.PSI_SALES_ENTER.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_RETRUN_ENTER.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_REPAIR_ENTER.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_TEST_ENTER.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_INVENTORY_PROFIT_ENTER.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_OTHER_ENTER.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_PURCHASE_ENTER.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_SALES_LEAVE.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_BORROW_LEAVE.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_REPAIR_LEAVE.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_TEST_LEAVE.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_INVENTORY_LOSS_LEAVE.getType() == examine.getCategoryType()
                                    || CrmEnum.PSI_OTHER_LEAVE.getType() == examine.getCategoryType()) {
                                // 出入库

                                is_examine_pass = true;

                            } else if (CrmEnum.FINANCE_PURCHASE.getType() == examine.getCategoryType()
                                    || CrmEnum.FINANCE_OFFICE_PURCHASE.getType() == examine.getCategoryType()
                                    || CrmEnum.FINANCE_NORMAL_PURCHASE.getType() == examine.getCategoryType()
                                    || CrmEnum.FINANCE_PROJECT_PURCHASE.getType() == examine.getCategoryType()
                                    || CrmEnum.FINANCE_DEV_PURCHASE.getType() == examine.getCategoryType()
                                    || CrmEnum.FINANCE_OTHER_PURCHASE.getType() == examine.getCategoryType()) {
                                // 采购申请

                                Db.update(Db.getSql("finance.purchase.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_OK.getType(), id);

                            }
                            // 报价
                            if (CrmEnum.CRM_QUOTATION_COMBINATION.getType() == examine.getCategoryType()) {
                                Db.update(Db.getSql("crm.quotationComb.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_OK.getType(), id);
                                //审核通过，更新对应商机的阶段至订单合同阶段
                                Kv kv2 = new Kv();
                                kv2.set("label",750).set("id",id).set("statusId",6);
                                updateBusinessStatusId(kv2);
                            }
                            break;
                    }
                }

            }
        }
        //线索审批通过，转换为客户
//        if(is_examine_pass && examine.getCategoryType() == 3) {
//        	R r = crmLeadsService.translate(id.toString(),newOwnerId,(customerType != null ? customerType : 1));
//        	Integer code = (Integer)r.get("code");
//        	if(code == 200) {
//        		Db.update(Db.getSql("crm.leads.updateCheckStatusById"),1,id);
//        		nowadayExamineLog.update();
//        		examineRecord.update();
//        	}
//        	return r;
//        }

        // 出入库审批通过，在库数量相应处理
        if (is_examine_pass && (PsiUtil.isLeaveStock(examine.getCategoryType()) || PsiUtil.isEnterStock(examine.getCategoryType()))) {

            Db.update(Db.getSql("psi.enterLeaveStock.updateCheckStatusById"), CheckStatusEnum.CHECK_STATUS_OK.getType(), id);

            // 进行在库相应处理
            msg = psiEnterLeaveStockService.updateStockpileByElsId(id);

            // 最后一次审核，更新快递及出库产品序列号
            if (PsiUtil.isLeaveStock(examine.getCategoryType()) && CrmEnum.PSI_INVENTORY_LOSS_LEAVE.getType() != examine.getCategoryType()) {

                psiEnterLeaveStockService.updateLeaveStockInfo(jsonObject);
            }
        }

        if (status != 4) {
            nowadayExamineLog.update();
        }
        return examineRecord.update() ? R.ok(msg) : R.error();
    }

    private void saveAdminExamineLog(String batchId, Long checkUserId, AdminExamineRecord examineRecord, AdminExamineStep examineStep) {
        AdminExamineLog examineLog = new AdminExamineLog();
        examineLog.setOrderId(examineStep.getStepNum());
        examineLog.setBatchId(batchId);
        examineLog.setLogId(null);
        examineLog.setExamineUser(checkUserId);
        examineLog.setCreateTime(DateUtil.date());
        examineLog.setCreateUser(BaseUtil.getUser().getUserId());
        examineLog.setExamineStatus(0);
        examineLog.setIsRecheck(0);
        examineLog.setExamineStepId(examineStep.getStepId());
        examineLog.setRecordId(examineRecord.getRecordId());
        examineLog.setMustCheck(1);
        examineLog.save();
    }
    
    // 审核通过时，更改商机的阶段状态
    private void updateBusinessStatusId(Kv kv) {
    	SqlPara sqlPara = Db.getSqlPara("crm.business.updateBusinessStatusId", kv);
    	SqlPara sqlPara2 = Db.getSqlPara("crm.business.selectBusinessByLabel", kv);
    	Db.update(sqlPara);
    	Record record = Db.findFirst(sqlPara2);
    	if(record != null && record.getInt("business_id") != null) {
    		CrmActionRecord crmActionRecord = new CrmActionRecord();
            crmActionRecord.setCreateUserId(BaseUtil.getUser().getUserId());
            crmActionRecord.setCreateTime(new Date());
            crmActionRecord.setTypes(CrmEnum.CRM_BUSINESS.getType() + "");
            crmActionRecord.setActionId(record.getInt("business_id"));
            ArrayList<String> strings = new ArrayList<>();
            Integer statusId = kv.getInt("statusId");
        	if(statusId == 3) {
            	strings.add("商机进入技术方案阶段3");
            }
            if(statusId == 6) {
            	strings.add("商机进入订单合同阶段6");
            }
            crmActionRecord.setContent(JSON.toJSONString(strings));
            crmActionRecord.save();
    	}
    }

    public R queryExamineLogList(Integer recordId) {
        //根据审核记录id查询审核记录
        AdminExamineRecord examineRecord = AdminExamineRecord.dao.findById(recordId);
        if (examineRecord == null) {
            //导入
            return R.ok();
        }
        AdminExamine adminExamine = AdminExamine.dao.findById(examineRecord.getExamineId());

        List<Record> logs = null;
        if (adminExamine.getExamineType() == 1) {
            logs = Db.find(Db.getSql("admin.examineLog.queryExamineLogByRecordIdByStep"), recordId);
        } else {
            logs = Db.find(Db.getSql("admin.examineLog.queryExamineLogByRecordIdByStep1"), recordId);
        }
        for (Record record : logs) {
            List<Record> files = Db.find(Db.getSql("admin.file.queryFilesByBatchId"), record.getStr("batch_id"));
            record.set("files", files);
        }
        return R.ok().put("data", logs);
    }

    /**
     * 根据审核记录id，查询审核日志
     * ownerUserId 负责人ID
     */
    public R queryExamineRecordList(Integer recordId, Long ownerUserId) {
        JSONObject jsonObject = new JSONObject();
        Record examineRecord = Db.findFirst(Db.getSql("admin.examineStep.queryExamineRecordById"), recordId);
        if (examineRecord == null) {
            //导入
            return R.ok();
        }
        //如果当前审批已撤回
        if (examineRecord.getInt("examine_status") == 4 || examineRecord.getInt("examine_status") == 5) {
            jsonObject.put("examineType", 1);
            List<Record> user = Db.find(Db.getSql("admin.examineLog.queryUserByRecordId"), recordId, examineRecord.getInt("examine_status"));

            if (examineRecord.getInt("examine_status") == 5) {
                examineRecord.set("examine_status", 6);
                user.forEach(record -> {
                    record.set("examine_status", 6);
                });
            }
            examineRecord.set("userList", user);
            List<Record> records = new ArrayList<>();
            records.add(examineRecord);
            jsonObject.put("steps", records);
            return R.ok().put("data", jsonObject);
        }
        AdminExamine adminExamine = AdminExamine.dao.findById(examineRecord.getInt("examine_id"));
        List<Record> list = new ArrayList<>();
        Record rec = Db.findFirst(Db.getSql("admin.examineLog.queryRecordAndId"), recordId);


        //当前审批人
        Long auditUserId = BaseUtil.getUser().getUserId();
        //jsonObject.put("isRecheck",0);
        //判断是否有撤回权限
        if ((auditUserId.equals(examineRecord.getLong("create_user")) || auditUserId.equals(BaseConstant.SUPER_ADMIN_USER_ID))
                && (examineRecord.getInt("examine_status") == 0 || examineRecord.getInt("examine_status") == 3)) {
            jsonObject.put("isRecheck", 1);
        } else {
            jsonObject.put("isRecheck", 0);
        }
        if (adminExamine.getExamineType() == 2) {
            Record log = Db.findFirst(Db.getSqlPara("admin.examineLog.queryRecordByUserIdAndStatus", Kv.by("create_user", rec.getInt("create_user")).set("examineTime", rec.getDate("examineTime"))));
            rec.set("examinUser", log);
            list.add(rec);
            //授权审批
            List<Record> logs = Db.find(Db.getSql("admin.examineLog.queryExamineLogAndUserByRecordId"), recordId);
            logs.forEach(r -> {
                Record l = Db.findFirst(Db.getSql("admin.examineLog.queryExamineLogAndUserByLogId"), r.getInt("log_id"));
                List<Record> files = Db.find(Db.getSql("admin.file.queryFilesByBatchId"), r.getStr("batch_id"));
                r.set("files", files);
                r.set("examinUser", l);
            });
            list.addAll(logs);
            //判断当前用户有没有权限审核
            Record reco = Db.findFirst(Db.getSqlPara("admin.examineLog.queryExamineLog",
                    Kv.by("recordId", recordId).set("auditUserId", auditUserId)));
            if (reco != null) {
                jsonObject.put("isCheck", 1);
            } else {
                jsonObject.put("isCheck", 0);
            }
            jsonObject.put("examineType", 2);
            jsonObject.put("steps", list);

        } else {
            jsonObject.put("examineType", 1);
            //固定审批
            List<Record> steps = Db.find("select * from yzcrm_admin_examine_step where  examine_id = ? ORDER BY step_num", adminExamine.getExamineId());
            //上一审核步骤
            Long lsatuUserId = null;
            for (Record step : steps) {
                List<Record> logs;
                if (step.getInt("step_type") == 1) {
                    //负责人主管
                    logs = Db.find(Db.getSql("admin.examineLog.queryUserByRecordIdAndStepIdAndStatus"), recordId, step.getInt("step_id"));
                    if (logs.size() == 1) {
                        if (logs.get(0).getInt("user_id") == null) {
                            logs = null;
                        }

                    }
                    //已经创建审核日志
                    if (logs != null && logs.size() != 0) {
                        for (Record record : logs) {
                            step.set("examine_status", record.getInt("examine_status"));
                            List<Record> files = Db.find(Db.getSql("admin.file.queryFilesByBatchId"), record.getStr("batch_id"));
                            record.set("files", files);
                        }
                        step.set("userList", logs);
                    } else {
                        step.set("examine_status", 0);
                        //还未创建审核日志
                        //查询负责人主管
                        List<Record> r = Db.find(Db.getSql("admin.examineLog.queryUserByUserId"), ownerUserId);
                        if (r.size() == 1) {
                            if (r.get(0).getInt("user_id") == null) {
                                r = null;
                            }

                        }
                        if (r == null || r.size() == 0) {
                            r = Db.find(Db.getSql("admin.examineLog.queryUserByUserIdAnd"), BaseConstant.SUPER_ADMIN_USER_ID);
                        }
                        step.set("userList", r);
                    }
                }else if(step.getInt("step_type") == 6){

                    //部门负责人
                    logs = Db.find(Db.getSql("admin.examineLog.queryUserByRecordIdAndStepIdAndStatus"), recordId, step.getInt("step_id"));
                    if (logs.size() == 1){
                        //                        没有审核记录
                        if (logs.get(0).getInt("user_id")==null){
                            logs = null;                        }                    }
                    //已经创建审核日志
                    if (logs != null && logs.size() != 0) {
                        for (Record record : logs) {
                            step.set("examine_status", record.getInt("examine_status"));
                            List<Record> files = Db.find(Db.getSql("admin.file.queryFilesByBatchId"),record.getStr("batch_id"));
                            record.set("files", files);                        }
                        step.set("userList", logs);
                    } else {
                        step.set("examine_status", 0);
                        //还未创建审核日志
                        //查询部门负责人
                        Record deptLeader = adminDeptService.getDeptLeader(ownerUserId);
                        ArrayList<Object> objects = new ArrayList<>();
                        objects.add(deptLeader);
                        if (deptLeader== null ) {
                            List<Record> records = Db.find(Db.getSql("admin.examineLog.queryUserByUserIdAnd"), BaseConstant.SUPER_ADMIN_USER_ID);
                            step.set("userList", records);
                        }else{
                            step.set("userList", objects);
                        }                    }}
                else if (step.getInt("step_type") == 2 || step.getInt("step_type") == 3) {//先判断是否已经审核过
                    logs = Db.find(Db.getSql("admin.examineLog.queryUserByRecordIdAndStepIdAndStatus"), recordId, step.getInt("step_id"));
                    if (logs != null && logs.size() != 0) {
                        //已经创建审核日志
                        int status = 0;

                        if (step.getInt("step_type") == 2) {
                            int i = 0;
                            boolean mustCheck = false; // 审核过程中后加的审批人未审
                            for (Record record : logs) {
                                if (record.getInt("examine_status") == 1) {
                                    status = 1;
                                }
                                if (record.getInt("examine_status") == 2) {
                                    i++;
                                }
                                if (record.getInt("examine_status") != 1 && record.getInt("must_check") == 1) {
                                    // 存在未审批的后加审批人
                                    mustCheck = true;
                                }
                                List<Record> files = Db.find(Db.getSql("admin.file.queryFilesByBatchId"), record.getStr("batch_id"));
                                record.set("files", files);
                            }
                            if (mustCheck == true) {
                                status = 0;
                            }
                            if (i == logs.size()) {
                                status = 2;
                            }
                        }
                        if (step.getInt("step_type") == 3) {
                            int i = 0;
                            for (Record record : logs) {
                                if (record.getInt("examine_status") == 2) {
                                    status = 2;
                                }
                                if (record.getInt("examine_status") == 1) {
                                    i++;
                                }
                                List<Record> files = Db.find(Db.getSql("admin.file.queryFilesByBatchId"), record.getStr("batch_id"));
                                record.set("files", files);
                            }
                            if (i == logs.size()) {
                                status = 1;
                            }
                        }
                        step.set("examine_status", status);
                        step.set("userList", logs);
                    } else {
                        //该步骤还未审核
                        logs = new ArrayList<>();
                        String[] userIds = step.getStr("check_user_id").split(",");
                        for (String userId : userIds) {
                            if (StrUtil.isNotEmpty(userId)) {
                                Record user = Db.findFirst(Db.getSql("admin.examineLog.queryUserByUserIdAndStatus"), userId);
                                if (user != null) {
                                    logs.add(user);
                                }
                            }
                        }
                        step.set("examine_status", 0);
                        step.set("userList", logs);
                    }
                } else {
                    //主管的主管
                    logs = Db.find(Db.getSql("admin.examineLog.queryUserByRecordIdAndStepIdAndStatus"), recordId, step.getInt("step_id"));
                    if (logs.size() == 1) {
                        if (logs.get(0).getInt("user_id") == null) {
                            logs = null;
                        }

                    }
                    //已经创建审核日志
                    if (logs != null && logs.size() != 0) {
                        for (Record record : logs) {
                            step.set("examine_status", record.getInt("examine_status"));
                            List<Record> files = Db.find(Db.getSql("admin.file.queryFilesByBatchId"), record.getStr("batch_id"));
                            record.set("files", files);
                        }
                        step.set("userList", logs);
                    } else {
                        step.set("examine_status", 0);
                        AdminUser adminUser = AdminUser.dao.findById(lsatuUserId);
                        if (adminUser != null && adminUser.getParentId() != null) {
                            logs = Db.find(Db.getSql("admin.examineLog.queryUserByUserIdAnd"), adminUser.getParentId());
                        } else {
                            logs = Db.find(Db.getSql("admin.examineLog.queryUserByUserIdAnd"), lsatuUserId);
                        }
                        //查询负责人主管的主管
                        step.set("userList", logs);
                    }
                }
                if (logs.size() > 0) {
                    lsatuUserId = logs.get(0).getLong("user_id");
                }
            }
            //判断当前用户有没有权限审核
            Record reco = Db.findFirst(Db.getSqlPara("admin.examineLog.queryExamineLog",
                    Kv.by("recordId", recordId).set("auditUserId", auditUserId).set("stepId", examineRecord.getInt("examine_step_id"))));
            if (reco != null) {
                jsonObject.put("isCheck", 1);
            } else {
                jsonObject.put("isCheck", 0);
            }
            List<Record> logs = Db.find(Db.getSqlPara("admin.examineLog.queryRecordByUserIdAndStatus", Kv.by("create_user", rec.getInt("create_user")).set("examineTime", rec.getDate("examineTime"))));
            rec.set("userList", logs);
            list.add(rec);
            list.addAll(steps);
            jsonObject.put("steps", list);
        }
        return R.ok().put("data", jsonObject);
    }

}
